const {ccclass, property} = cc._decorator;

@ccclass
export default class TabView extends cc.Component {
    @property(cc.Node)
    tab:cc.Node = null;
    @property(cc.Node)
    content:cc.Node = null;
    private normalColor:cc.Color = new cc.Color(255,255,255)
    private selectColor:cc.Color = new cc.Color(128,128,128)
    private selectButton(id:string) {
        for (const key in this.btnArray) {
            if (this.btnArray.hasOwnProperty(key)) {
                const btn:cc.Node = this.btnArray[key]
                btn.color = this.normalColor
            }
        }
        let btn:cc.Node = this.btnArray[id];
        btn.color = this.selectColor

    }
    private showViewById(id:string)
    {
        const targetView:cc.Node = this.viewArray[id]
        if (targetView)
        {
            targetView.active = true
        }
    }
    private hideAllView() {
        for (const key in this.viewArray) {
            if (this.viewArray.hasOwnProperty(key)) {
                const view:cc.Node = this.viewArray[key]
                view.active = false
            }
        }
    }
    private onTouch(event:cc.Event.EventTouch)
    {
        let btn:cc.Node = event.currentTarget
        let btnName:string = btn.name
        let id:string = btnName.slice(3,btnName.length)
        this.selectIndex = Number(id)
    }
    private btnArray:Array<cc.Node> = []
    private onTab() {
        for (const key in this.tab.children) {
            if (this.tab.children.hasOwnProperty(key)) {
                const btn:cc.Node = this.tab.children[key];
                let id:string = btn.name.slice(3,btn.name.length)
                this.btnArray[id] = btn
                btn.on(cc.Node.EventType.TOUCH_END,this.onTouch,this)
            }
        }
    }
    private viewArray:Array<cc.Node> = []
    private onContent() {
        for (const key in this.content.children) {
            if (this.content.children.hasOwnProperty(key)) {
                const view:cc.Node = this.content.children[key];
                let id:string = view.name.slice(4,view.name.length)
                this.viewArray[id] = view
            }
        }
    }
    onLoad()
    {
        this.onTab()
        this.onContent()
    }
    start () {
        this.hideAllView()
        this.selectIndex = 0
    }
    private _selectIndex:number
    public set selectIndex(v : number) {
        this.hideAllView();
        this.showViewById(v.toString());
        this.selectButton(v.toString())
        this._selectIndex = v;
    }
    
    public get selectIndex() : number {
        return this._selectIndex
    }
    
    
}
